# !/usr/bin/env python
# -*- coding: utf-8 -*-
"""
 -------------------------------------------------
    File Name:     run_engine.py
    Description:   执行引擎模块: 运行测试用例，生成报告
 -------------------------------------------------
 """
from typing import Literal

import pytest

from apitesting.common.util.logger import log
from apitesting.config import settings, paths
from apitesting.src.startup import (
    validate_case_path,
    configure_html_report,
    configure_allure_report,
    configure_max_fail,
    configure_additional_args,
    format_run_args
)

__all__ = ['setup_check_run_args', 'start_run']


def setup_check_run_args(
        *args,
        log_level: Literal['-q', '-s', '-v', '-vv', '--tb=no'] = '-s',
        test_dir: str | None = None,
        html_report: bool = True,
        allure: bool = True,
        allure_clear: bool = True,
        max_fail: int = 0,
        x: bool = False,
        strict_markers: bool = False,
        capture: bool = True,
        disable_warnings: bool = True,
        **kwargs,
) -> list:
    """运行启动程序
    该函数负责根据提供的参数启动测试运行环境，并根据指定的配置生成测试报告和通知。
    """

    log.info("初始化运行参数")

    # 初始化运行参数列表
    run_args = [log_level]
    # 验证并处理用例路径参数，将运行路径添加到运行参数列表中
    run_path = validate_case_path(test_dir)
    run_args.append(run_path)

    run_args.extend(
        # 处理HTML报告生成配置
        configure_html_report(html_report)
        # 处理Allure报告生成配置
        + configure_allure_report(allure=allure, allure_clear=allure_clear)
        # 处理最大失败案例数配置
        + configure_max_fail(max_fail)
    )

    # 处理立即停止测试运行配置
    if x:
        run_args.append('-x')

    # 处理严格检查测试标记配置
    if strict_markers:
        run_args.append('--strict-markers')

    # 处理捕获标准输出和错误输出配置
    if capture:
        run_args.append('--capture=tee-sys')

    # 处理禁用警告配置
    if disable_warnings:
        run_args.append('--disable-warnings')

    # 处理额外的位置参数和关键字参数
    configure_additional_args(args=args, kwargs=kwargs, run_args=run_args)

    # print(run_args)

    # 格式化运行参数，确保参数值被正确地包含在引号中
    run_pytest_command_args = format_run_args(run_args=run_args)

    log.info(f' ✅ 运行参数格式化成功')
    log.info(
        f'开始运行项目：{settings.project.name}' if run_path == str(
            paths.TEST_CASE_DIR / settings.project.name) else f'开始运行项目：{run_path}'
    )
    log.debug(f'Pytest CLI: \npytest {run_pytest_command_args}')

    return run_args


def start_run(pytest_args):
    """运行测试用例"""
    # pytest_args = [test_dir, f"--html={report_file}", "--self-contained-html"]
    pytest.main(pytest_args)
